package com.stylefeng.guns.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.persistence.dao.*;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.system.service.ITTrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-03-07
 */
@Service
@Transactional
public class TTrainServiceImpl extends ServiceImpl<TTrainMapper, TTrain> implements ITTrainService {

    @Autowired
    TTrainMapper tTrainMapper;

    @Autowired
    TBillMapper billMapper;

    @Autowired
    TOrderMapper orderMapper;

    @Autowired
    TOrderFeeMapper orderFeeMapper;

    @Autowired
    TMonthbalanceDetailMapper tmonthbalanceDetailMapper;

    @Autowired
    private DictMapper tDictMapper;

    @Override
    public List<Map<String, Object>> checkTrainList(Pagination pagination, String beginTime, String endTime, String name,String status,String dot_id) {
        return tTrainMapper.checkTrainList(pagination,beginTime,endTime,name,status,dot_id);
    }

    @Override
    public List<Map<String, Object>> checkTrainDirsList(Pagination pagination, String beginTime, String endTime, String name, String status, String dot_id) {
        return tTrainMapper.checkTrainDirsList(pagination,beginTime,endTime,name,status,dot_id);
    }

    @Override
    public List<Map<String, Object>> checkTrainZZList(Pagination pagination, String beginTime, String endTime, String name, String status, String dot_id) {
        return tTrainMapper.checkTrainZZList(pagination,beginTime,endTime,name,status,dot_id);
    }

    @Override
    public Map<String, Object> checkTrainZZListGroup(Pagination pagination, String beginTime, String endTime, String name, String status, String dot_id) {
        return tTrainMapper.checkTrainZZListGroup(pagination,beginTime,endTime,name,status,dot_id);
    }

    @Override
    public List<Map<String, Object>> checkTrainDetailList( String batch_no) {
        return tTrainMapper.checkTrainDetailList(batch_no);
    }

    @Override
    public List<Map<String, Object>> checkTrainDisDetailList(String batch_no) {
        return tTrainMapper.checkTrainDisDetailList(batch_no);
    }

    @Override
    public List<Map<String, Object>> checkTrainZZDetailList(String batch_no) {
        return tTrainMapper.checkTrainZZDetailList(batch_no);
    }

    @Override
    public void checkTrain(TTrain tTrain, TBill bill,String mA,String mB,String mC,String mD,String mE,String xj,String gz) {
        TTrain t1 =new TTrain();
        t1.setTrainNo(tTrain.getTrainNo());
        TTrain t=tTrainMapper.selectOne(t1);
        Map param1=new HashMap();
        param1.put("dot_id",ShiroKit.getUser().getDotId());
        param1.put("nType", Const.NTYPE_04); // 类别 00 初始 01 配送 02 中转 03 自提  04 月结
        String bath_no = tDictMapper.getNumCode(param1);
        //插入现结记录插入balance表
        TMonthbalanceDetail md=new TMonthbalanceDetail();
        md.setCreater(ShiroKit.getUser().getId());
        md.setDotId(ShiroKit.getUser().getDotId());
        md.setIncome(1);//来源 1，收货，2，自提，3，配送，4，中转，5，改单
        md.setStatus("1");//0待结算 1 已结算
        md.setSettlementType(0);//付款方式，0现结 1月结
        md.setMoney(Double.parseDouble(xj));
        md.setTraner(t.getSendDeptName());
        md.setIncomeId(t.getId());
        md.setIncomeName(t.getTrainNo());
        md.setBalance_num(bath_no);
        tmonthbalanceDetailMapper.insert(md);

        //插入现结记录插入balance表
        TMonthbalanceDetail m=new TMonthbalanceDetail();
        m.setCreater(ShiroKit.getUser().getId());
        m.setDotId(ShiroKit.getUser().getDotId());
        m.setIncome(1);//来源 1，收货，2，自提，3，配送，4，中转，5，改单
        if("0".equals(gz)) {
            //月结费用为0 直接为已结算
            m.setStatus("1");//0待结算 1 已结算
        }else{
            m.setStatus("0");
        }
        m.setSettlementType(1);//付款方式，0现结 1月结
        m.setMoney(Double.parseDouble(gz));
        m.setTraner(t.getSendDeptName());
        m.setIncomeId(t.getId());
        m.setIncomeName(t.getTrainNo());
        m.setBalance_num(bath_no);
        tmonthbalanceDetailMapper.insert(m);

        //1 、生成流水号 2、只更新和上家结算的费用
        EntityWrapper<TOrder> eWrapper = new EntityWrapper<TOrder>();
        eWrapper.where("bacth_id={0}",tTrain.getId());
        List<TOrder> orders=orderMapper.selectList(eWrapper);
        //结算方式 isType=0 查当场结算的   isType=1 查所有费用
        List<Map<String,Object>> updateFeeids=tTrainMapper.selectUpFeeid(tTrain.getTrainNo(),"2","1");

        int i=billMapper.insert(bill);

        if(updateFeeids.size()>0){
                //费用为0 无需更新
                TMonthbalanceDetail md_xj=new TMonthbalanceDetail();
                md_xj.setId(md.getId());
                md_xj.setBillId(bill.getId());
                tmonthbalanceDetailMapper.updateById(md_xj);
               for(Map map:updateFeeids){
                    TOrderFee tOrderFee=new TOrderFee();
                    //settlement_type 结算方式 0 当场结算 1 月结
                    String settlementType="1";
                    if("0".equals(settlementType)){
                        tOrderFee.setBalance_id(md.getId());
                    }else{
                        tOrderFee.setBalance_id(m.getId());
                    }
                    tOrderFee.setSettlementType(settlementType);
                    tOrderFee.setAuditStatus(1);//0 未结算 1 已结算 2 坏账 3 清账
                    tOrderFee.setId(Integer.valueOf(map.get("id").toString()));
                    orderFeeMapper.updateById(tOrderFee);
                }
                for(TOrder order:orders){
                    order.setStatus(1);//订单状态 0-审核中 1-待出库 2-已出库 3-完成
                    order.setFlow_status(1); //0 开单 1 车次核销 2 出库 3 收银 4 核销
                    order.setCheckUserId(bill.getEditUser()+"");
                    orderMapper.updateById(order);
                }
            tTrainMapper.updateById(tTrain);

        }

    }
   //中转核销
    @Override
    public void transferHX(String id, String mon_bal_fee) {

        Map param=new HashMap();
        param.put("dot_id",ShiroKit.getUser().getDotId());
        param.put("nType", Const.NTYPE_04); // 类别 00 初始 01 配送 02 中转 03 自提  04 月结
        String bath_no = tDictMapper.getNumCode(param);

        TTrain train=tTrainMapper.selectById(id);
        //1，插入balancedetail表 billid为空 setlement 为0，status 为1
        //2，更新月结费用的orderfee 表的balanceID
        TMonthbalanceDetail m=new TMonthbalanceDetail();
        m.setCreater(ShiroKit.getUser().getId());
        m.setDotId(ShiroKit.getUser().getDotId());
        m.setIncome(4);//来源 1，收货，2，自提，3，配送，4，中转，5，改单
        if("0".equals(mon_bal_fee)){
            m.setStatus("1");//0待结算 1 已结算
        }else{
            m.setStatus("0");//0待结算 1 已结算
        }

        m.setSettlementType(1);//付款方式，0现结 1月结
        m.setMoney(Double.parseDouble(mon_bal_fee));
        m.setTraner(train.getSendDeptName());
        m.setIncomeId(train.getId());
        m.setIncomeName(train.getTrainNo());
        m.setBalance_num(bath_no);
//        m.setBalance_num("YJ"+ ShiroKit.getUser().getId()+"_"+ DateUtil.getAllTimes());
        tmonthbalanceDetailMapper.insert(m);

        EntityWrapper<TOrder> entityWrapper=new EntityWrapper<>();
        entityWrapper.where("train_id={0}",id);
        List<TOrder> orders=orderMapper.selectList(entityWrapper);
        for(TOrder order:orders){
            EntityWrapper<TOrderFee> eWrapper = new EntityWrapper<TOrderFee>();
            eWrapper.where("order_id={0}",order.getId()+"");
            List<TOrderFee> orderFees=orderFeeMapper.selectList(eWrapper);
            for(TOrderFee tOrderFee:orderFees){

                tOrderFee.setAuditStatus(3);//0 未结算 1 已结算 2 坏账 3 清账
                //32 33 34 35 36 43 中转时下游网点费用
                if(tOrderFee.getSettlementType()!=null&&tOrderFee.getSettlementType().equals("1")&&
                        ( (32==tOrderFee.getFeeId())||(33==tOrderFee.getFeeId())||(34==tOrderFee.getFeeId())||(35==tOrderFee.getFeeId())||(36==tOrderFee.getFeeId())||(43==tOrderFee.getFeeId()) )  )//月结
                    tOrderFee.setBalance_id(m.getId());

                //todo 操作人
                orderFeeMapper.updateById(tOrderFee);
            }
            order.setFlow_status(4);
            orderMapper.updateById(order);//0 开单 1 车次核销 2 出库 3 收银 4 核销
        }
        TTrain tTrain=new TTrain();
        tTrain.setId(Integer.valueOf(id));
        tTrain.setStatus(1);// 0 未核销 1 核销 2 配送  3已付款
        tTrainMapper.updateById(tTrain);

    }
    @Override
    public void checkTrainDis(TTrain tTrain, TBill bill,String ys) {
        TTrain train =tTrainMapper.selectById(tTrain.getId());
        //1 、生成流水号 2、只更新和上家结算的费用
        EntityWrapper<TOrder> eWrapper = new EntityWrapper<TOrder>();
        eWrapper.where("train_id={0}",tTrain.getId());
        List<TOrder> orders=orderMapper.selectList(eWrapper);

        List<Map<String,Object>> updateFeeids=tTrainMapper.selectUpFeeid(tTrain.getTrainNo(),"3","0");
        int i = billMapper.insert(bill);
        if(updateFeeids.size()>0){
            Map param1=new HashMap();
            param1.put("dot_id",ShiroKit.getUser().getDotId());
            param1.put("nType", Const.NTYPE_04); // 类别 00 初始 01 配送 02 中转 03 自提  04 月结
            String bath_no = tDictMapper.getNumCode(param1);

            TMonthbalanceDetail m=new TMonthbalanceDetail();
            m.setCreater(ShiroKit.getUser().getId());
            m.setDotId(ShiroKit.getUser().getDotId());
            m.setIncome(3);//来源 1，收货，2，自提，3，配送，4，中转，5，改单
            m.setStatus("1");//0待结算 1 已结算
            m.setSettlementType(0);//付款方式，0现结 1月结
            m.setMoney(Double.parseDouble(ys));
            m.setTraner(train.getDriverName());
            m.setIncomeId(train.getId());
            m.setIncomeName(train.getTrainNo());
            m.setBillId(bill.getId());
//            m.setBalance_num("XJ"+ ShiroKit.getUser().getId()+"_"+ DateUtil.getAllTimes());
            m.setBalance_num(bath_no);
            tmonthbalanceDetailMapper.insert(m);

            for(Map map:updateFeeids){
//                Map param =new HashMap();
//                param.put("order_fee_id",map.get("id").toString());
//                param.put("order_id",map.get("order_id").toString());
//                param.put("bill_id",bill.getId());
//                tTrainMapper.addFeeBill(param);

                TOrderFee tOrderFee=new TOrderFee();
                tOrderFee.setSettlementType("0");
                tOrderFee.setAuditStatus(1);
                tOrderFee.setBalance_id(m.getId());
                tOrderFee.setId(Integer.valueOf(map.get("id").toString()));
                orderFeeMapper.updateById(tOrderFee);
            }

            for(TOrder order:orders){
                if(ys!=null&&!"0".equals(ys)) {
                    order.setStatus(2);
                    order.setFlow_status(3); //0 开单 1 车次核销 2 出库 3 收银 4 核销
                }else{
                    order.setStatus(3);
                    order.setFlow_status(4); //0 开单 1 车次核销 2 出库 3 收银 4 核销
                }
                order.setCheckUserId(bill.getEditUser()+"");
                if (order.getReceipt() == null || order.getReceipt().equals("")) {
                    order.setReceiptStatus(1);
                }
                orderMapper.updateById(order);
            }
            tTrainMapper.updateById(tTrain);

        }
    }
}
